// packageB/pages/Collection_package/Collection_package.js
import { ml_hideLoading, ml_showLoading, ml_showToast, ml_Toast } from '../../../utils/asyncWX'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time1: 0,
    choise_time: ['中午 (12:30~13:30)', '傍晚 (17:30~18:30)', '晚上 (21:00~22:00)'],
    means: true,
    iconshow: false,
    address: { 'userName': '请选择地址', 'del': '请填写清楚具体的楼栋和层数', 'telNumber': '', 'state': false }, //用户收件地址
    num1: 0,   //快件类型
    num2: null,   //快件大小
    express_remarks: '', //快件备注
    express_code: '',
    price_inf: null,
    login_coupon: null,  // 优惠卷信息
    indexpack1: 0,
    express: ['邮政', '菜鸟驿站', '京东', '顺丰', '天猫超市快递'],
    timepack1: ['快递代拿', '外卖代拿', '校园代购'],
    timepack1_tip: [{ title: '取件码', tips: '请复制取件码或取件短信+收件人姓名（比如：1-3-789（李四）收件人要与快递上一致），多件收件码可用逗号隔开，价格按总重量计算选择。' }, { title: '物品信息', tips: '请详细填写购买地址与物品信息' }, { title: '需求', tips: '请填写清楚那代购什么以及地点？由快递员和你确认后向快递员付清商品费用！' }],
    mailsize: ['小件(￥1.5，<1kg)', '小中件(￥2.0，1~2kg)', '小大件（￥3.0，2~3kg）', '中小件（￥3.5，3~5kg）', '中件（￥4.5，5~10kg）', '大件（￥5.5，10~15kg）', '超大件（￥7.0，15~20kg）']
  },

  //更改取件方式
  means() {
    this.setData({ means: !this.data.means });
    if (this.data.num2 != null) {
      this.prices();
    }
  },
  //用户 快件协议
  iconargee() {
    this.setData({ iconshow: !this.data.iconshow });
  },
  lookagreement() {
    wx.navigateTo({
      url: '/packageB/pages/login_looking/login_looking',
    })
  },
  PickerChange1: function (e) {
    this.setData({
      num1: e.detail.value
    })
  },
  PickerChange4: function (e) {
    this.setData({
      time1: e.detail.value
    })
  },

  get_price(value) {
    let login_coupon = this.data.login_coupon;
    let pay_number, coupon_number;
    if (login_coupon == '') {
      pay_number = value;
    } else {
      if (login_coupon.collar_inf.user_type == 'deduction') {
        if (login_coupon.collar_inf.order_number >= value) {
          pay_number = value;
        } else {
          pay_number = Number(value) - Number(login_coupon.collar_inf.order_number);
        }
      } else if (login_coupon.collar_inf.user_type == 'discount') {
        pay_number = Number(value) * (Number(login_coupon.collar_inf.order_number) * 0.1);
      }
    }
    pay_number = Math.round(pay_number * 100) / 100;
    coupon_number = Math.round((value - pay_number) * 100) / 100;
    return { pay_number, coupon_number };
  },
  // 价格
  prices() {
    let indexed = this.data.indexed;
    let store_price, pay_price, ifadd = this.data.means ? 1 : 1.5;
    switch (indexed) {
      case '0': { store_price = 1.5 * ifadd; pay_price = this.get_price(1.5 * ifadd); break; }
      case '1': { store_price = 2.0 * ifadd; pay_price = this.get_price(2.0 * ifadd); break; }
      case '2': { store_price = 3.0 * ifadd; pay_price = this.get_price(3.0 * ifadd); break; }
      case '3': { store_price = 3.5 * ifadd; pay_price = this.get_price(3.5 * ifadd); break; }
      case '4': { store_price = 4.5 * ifadd; pay_price = this.get_price(4.5 * ifadd); break; }
      case '5': { store_price = 5.5 * ifadd; pay_price = this.get_price(5.5 * ifadd); break; }
      case '6': { store_price = 7.0 * ifadd; pay_price = this.get_price(7.0 * ifadd); break; }
    }
    this.setData({
      price_inf: { 'store_price': store_price, 'pay_price': pay_price.pay_number, 'coupon_number': pay_price.coupon_number }
    })
  },

  PickerChange2: function (e) {
    let indexed = e.detail.value;
    this.setData({
      num2: e.detail.value,
      indexed: indexed
    })
    this.prices();
  },
  timeChange2(e) {
    this.setData({
      indexpack1: e.detail.value
    })
  },

  //选择地址
  choose_address() {
    var that = this;
    wx.chooseAddress({
      success(res) {
        console.log(res)
        // let dels = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        let dels = res.detailInfo;
        that.setData({ address: { userName: res.userName, telNumber: res.telNumber, del: dels, state: true } })
      }
    })
  },
  //备注
  textareaBInput(e) { this.setData({ express_remarks: e.detail.value }); },
  express_code(e) { this.setData({ express_code: e.detail.value }); },
  //支付函数
  async payment(value) {
    //拉起支付
    console.log(value)
    let res = await wx.cloud.callFunction({
      name: 'payment', data: {
        type: 'pay_money',
        orderid: value.orderid,
        money: value.money * 100, //分做单位的
        title: value.title
      }
    })
    let res1 = await wx.requestPayment({
      timeStamp: res.result.timeStamp,
      nonceStr: res.result.nonceStr,
      package: res.result.package,
      signType: 'MD5',
      paySign: res.result.paySign,
    })
    console.log(res);
    console.log(res1);
    if (res1.errMsg == "requestPayment:ok") {
      ml_showToast('支付成功');
      return { 'code': 200, 'datas': res1 };
    } else {
      ml_Toast('支付失败！请重新尝试支付！');
      return { 'code': 400, 'datas': res1 };
    }
  },


  //提交订单
  async submit() {
    let text = this.ifnone();
    let pay_time = + new Date();  //订单创建时间
    if (this.ifnone() == 200) {
      let pay_orderinf = {
        address2: this.data.address,
        dispatchin_type: this.data.means ? '普通配送' : '急件配送',
        order_types: this.data.express[this.data.num1],
        order_sizes: this.data.mailsize[this.data.num2],
        order_typepack: this.data.timepack1[this.data.indexpack1],
        order_express_code: this.data.express_code,
        choise_time: this.data.choise_time[this.data.time1],
        express_remarks: this.data.express_remarks
      }
      console.log(pay_orderinf)
      //支付
      let value = {
        orderid: pay_time + 'gold',
        money: Number(this.data.price_inf.pay_price),
        // money: 0.01,
        title: '一运校园物流收款专用'
      };
      ml_showLoading();
      //判断订单优惠金额是否正确
      let get_paynumber = await wx.cloud.callFunction({
        name: 'pass_coupon', data: {
          pay_money: this.data.price_inf.store_price,
          type: 'hedui',
          coupon_id: this.data.login_coupon == '' ? '' : this.data.login_coupon._id
        }
      })
      if (get_paynumber.result.return_data.pay_number != this.data.price_inf.pay_price) {
        ml_Toast('价格核对失败')
        return;
      }
      ml_hideLoading();
      //调用支付
      let pay_result = await this.payment(value);
      //支付成功
      if (pay_result.code == 200) {
        ml_showLoading();
        var data_list = {
          _openid: wx.getStorageSync('openid'),
          pay_time: pay_time,
          pay_orderinf: pay_orderinf,
          pay_aftermoney: this.data.price_inf.store_price,
          pay_money: this.data.price_inf.pay_price,
          order_number: pay_time + 'gold',
          coupon_inf: this.data.login_coupon == '' ? {} : this.data.login_coupon
        }
        let coupon_id = this.data.login_coupon;
        //记录数据库
        let res = await wx.cloud.callFunction({
          name: 'daisho_list', data: {
            type: 'addwait',
            data_list: data_list,
            coupon_id: coupon_id == '' ? '' : coupon_id._id
          }
        })
        console.log(res)
        if (res.result.add_list.errMsg == 'collection.add:ok') {
          ml_showToast('下单成功');
          this.setData({
            address: { 'userName': '请选择地址', 'del': '请填写清楚具体的楼栋和层数', 'telNumber': '', 'state': false }, //用户收件地址
            num1: 0,   //快件类型
            num2: null,   //快件大小
            express_remarks: '', //快件备注
            express_code: '',
            price_inf: null,
            login_coupon: null,  // 优惠卷信息
            indexpack1: 0,
            means: true,
            iconshow: false
          });
          this.getdatas();
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageC/pages/wait_right/wait_right',
            })
          }, 1000);
        } else {
          ml_Toast('记录数据失败！请联系客服！');
        }
      }
    } else {
      ml_Toast(text);
    }
  },
  // 判断是否
  ifnone() {
    if (!this.data.address.state) { return '请选择地址'; }
    if (this.data.num2 == null) { return '请选择快件大小'; }
    if (this.data.express_code == '') { return '请输入取件码'; }
    if (!this.data.iconshow) { return '请勾选用户快件协议！'; }
    return 200
  },
  async getdatas() {
    let openid = wx.getStorageSync('openid');
    var DB = wx.cloud.database();
    const _ = DB.command;
    let login_coupon;
    var res2 = await DB.collection('login_coupon').where({ login_openid: openid, 'collar_inf.type_order': 'collection', over_time: _.gte(+new Date()) }).get();
    console.log(res2.data);
    if (res2.data.length == 0) { login_coupon = ''; }
    else { login_coupon = res2.data[0]; }
    this.setData({ login_coupon: login_coupon })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getdatas();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})